<?php

namespace oss;

use app\common\lib\RespCode;
use OSS\OssClient;
use OSS\Core\OssException;
use think\Exception;
use think\facade\Env;

class Oss { 
    /**
     * 配置
     * @var array
     */
    public static $config = [
        'accessKeyId'     => 'LTAI4FzinZX9M4GFP3Sxbg6h',
        'accessKeySecret' => 'x97sjRShDynRZXxH63lfz0wY1U8tPX',
        'endpoint'        => 'http://oss-cn-chengdu.aliyuncs.com',
        'domain'          => 'https://oss.fpaiyun.com',
        'bucket'          => 'fpy-erp',
    ];

    /**
     * 当前对象
     * @var
     */
    protected static $instance;

    /**
     * oss对象
     * @var
     */
    protected static $ossClient;

    /**
     * 上传到oss的路径
     * @var
     */
    protected $filename;

    private function __construct() {
        self::$ossClient = new OssClient(self::$config['accessKeyId'], self::$config['accessKeySecret'], self::$config['endpoint']);
    }

    public static function getInstance() {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 生成oss文件路径
     * @param $prefix
     * @param $ext
     * @return string
     */
    public function createFilename($prefix, $ext) {
        $this->filename = "{$prefix}/" . date('Y-m-d') . "/" . uniqid12() . ".{$ext}";
        return self::$config['domain'] . "/" . $this->filename;
    }

    /**
     * 上传oss
     * @param $filePath
     * @return bool
     * @throws Exception
     */
    public function uploadFile($filePath) {
        try {
            self::$ossClient->uploadFile(self::$config['bucket'], $this->filename, $filePath);
            return true;
        } catch (OssException $e) {
            throw new Exception('OSS上传失败',RespCode::PARAMS_ERR);
            return false;
        }
    }

    /**
     * 上传流
     * @param $content
     * @return bool
     * @throws Exception
     */
    public function putObject($content){
        try {
            self::$ossClient->putObject(self::$config['bucket'], $this->filename, $content);
            return true;
        } catch (OssException $e) {
            throw new Exception('OSS上传失败',RespCode::PARAMS_ERR);
            return false;
        }
    }

    /**
     * 删除文件
     * @param $fileName
     * @return bool
     * @throws Exception
     */
    public function delOneFile($fileUrl){
        try {
            //正式环境才能删除文件
            if(Env::get ('app.dev','dev') !='dev'){
                $dmon=self::$config['domain'].'/';
                $fileUrl=str_replace($dmon,"",$fileUrl);
                self::$ossClient->deleteObject(self::$config['bucket'], $fileUrl);
                return true;
            }
        } catch (OssException $e) {
            throw new Exception('OSS删除失败',RespCode::PARAMS_ERR);
            return false;
        }
    }
}